package com.theaf.basemodule.dao;

import com.theaf.basemodule.common.model.SysResource;
import com.theaf.core.repo.base.BaseRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

/**
 * @Author:songwenke
 * @Description:
 * @Date:create in 17:01 2018/1/3
 * @Modified By:
 **/
public interface ResourceDAO extends BaseRepository<SysResource,Long> {
    /**
     * 查询用户有权限的功能数据
     * @param userId
     * @return
     */
    @Query(nativeQuery=true,value = "select t.id from sys_resource t where t.enable=true and t.type=3 and " +
            //岗位有权限
            "(exists(select * from sys_pos_auth a,sys_user b where a.pos_id=b.pos_id and b.id=:userId and a.res_id=t.id) or " +
            //用户调整加的权限或权限本身缺省有的权限
            "exists(select * from sys_use_auth a where a.use_id=:userId and a.adjust_type=1 and t.id=a.res_id) or t.default_val=true)"+
            //但不包括用户调整减的权限
            " and not exists(select * from sys_use_auth a where a.use_id=:userId and a.adjust_type=2 and t.id=a.res_id)")
    List<Long> findUserFun(@Param("userId") Long userId);

    /**
     * 查询岗位对应的资源
     * @param posId
     * @return
     */
    @Query(nativeQuery=true,value = "select t.id from sys_resource t where t.enable=true and " +
            "exists(select * from sys_pos_auth a where a.pos_id=:posId and a.res_id=t.id)")
    List<Long> findPosFun(@Param("posId") Long posId);

    /**
     * 查询用户对应的和缺省的功能
     * @param userId
     * @return
     */
    @Query(nativeQuery=true,value = "select t.id from sys_resource t where t.enable=true and " +
            "(t.default_val=true or exists(select * from sys_pos_auth a,sys_user b where b.pos_id=a.pos_id and b.id=:userId and a.res_id=t.id))")
    List<Long> findUserFunAddDefaultFun(@Param("userId") Long userId);

    /**查询模块和功能信息**/
    @Query(nativeQuery=true,value = "select t.name moduelName,y.id funId,y.name funName " +
            "from sys_resource t,sys_resource y where t.enable=true and " +
            "y.enable = true and t.id=y.pid and t.pid=:appId order by t.name,y.name")
    List<Object[]> findAuthByApp(@Param("appId") Long appId);
}
